#ifndef __BASE_STRUCTURE_LINUX_LIST_H
#define __BASE_STRUCTURE_LINUX_LIST_H

#include <stdio.h>
#include <stddef.h>

/* 模仿 linux Kernel 的侵入式链表 */

struct list_head {
        struct list_head *prev, *next;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)

#define INIT_LIST_HEAD(ptr) ( (ptr)->prev = (ptr), (ptr)->next = (ptr) )

#define container_of(ptr, type, member) (                           \
        (type*)((char*)((type*)(ptr)) - offsetof(type, member)) )

#define list_entry(ptr, type, member) container_of(ptr, type, member)

static inline
void __list_add(struct list_head *newnode,
                struct list_head *prev, struct list_head *next)

{
        newnode->prev = prev;
        prev->next = newnode;
        next->prev = newnode;
        newnode->next = next;
}

static inline
void list_add(struct list_head *newnode, struct list_head *head) {
        __list_add(newnode, head, head->next);
}

static inline
void list_add_tail(struct list_head *newnode, struct list_head *head) {
        __list_add(newnode, head->prev, head);
}

static inline
void __list_del(struct list_head *prev, struct list_head *next) {
        prev->next = next;
        next->prev = prev;
}

static inline
void list_del_entry(struct list_head *entry) {
        __list_del(entry->prev, entry->next);
}

static inline
void list_del(struct list_head *entry) {
        __list_del(entry->prev, entry->next);
        entry->prev = NULL;
        entry->next = NULL;
}

static inline
void list_del_init(struct list_head *entry) {
        list_del_entry(entry);
        INIT_LIST_HEAD(entry);
}

#define list_is_empty(list) ((list)->next == list)

#define list_for_each_entry(iterator, head, type, member)               \
        for ( (iterator) = list_entry((head)->next, type, member);      \
              &((iterator)->member) !=  (head);                         \
              (iterator) = list_entry((iterator)->member.next, type, member)  )

#endif
